#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys
import subprocess
import json


class DeviceType:

    def __init__(self):
        self.work_dir = os.path.dirname(os.path.realpath(__file__))
        self.code_root = self._get_config("code_root")
        self.xts_root = self._get_config("xts_root")
        self.devicetypes = self._get_config("devicetypes")
        self.modules = self._get_config("product_components")

    def _get_config(self, key):
        with open('config.json', 'r') as rf:
            mydict = json.load(rf)
            return mydict.get(key)

    def get_all_projects(self):
        cmd = "./get_hvigor_projects.sh {}".format(self.xts_root)
        ret = subprocess.run([cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
        projects = ret.stdout.decode().strip().split('\n')
        return projects

    def get_module_name_of_project(self, project_directory):
        gn_file = os.path.join(project_directory, "BUILD.gn")
        cmd = './get_module_name.sh {}'.format(gn_file)
        ret = subprocess.run([cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
        module_name = ret.stdout.decode().strip().split('\n')[0]
        if not module_name:
            print("error: cannot find part_name from {}".format(gn_file))
        return module_name

    # def get_indent(self, cfg_file):
    #     cmd = "./get_indent.sh {}".format(cfg_file)
    #     ret = subprocess.run([cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    #     indent = ret.stdout.decode().strip()
    #     return indent

    # def is_dos_format(self, cfg_file):
    #     cmd = "./is_dos_format.sh {}".format(cfg_file)
    #     ret = subprocess.run([cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    #     is_dos = ret.stdout.decode().strip()
    #     return is_dos

    def get_config_file_list(self, project_directory):
        cmd = "./get_config_json_list.sh {}".format(project_directory)
        ret = subprocess.run([cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
        ret_str = ret.stdout.decode().strip()
        if ret_str:
            cfg_file_list = ret_str.split('\n')
        else:
            print("Error: Cannot find config from {}".format(project_directory))
            cfg_file_list = []
        return cfg_file_list

    def update_devicetype_to_config_json(self, cfg_file):
        cmd = "././update_config_json.sh {}".format(cfg_file)
        ret = subprocess.run([cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
        if ret.returncode:
            print("Error: Update DeviceType failed in {}".format(cfg_file))

    def update_devicetype_to_module_json5(self, cfg_file):
        cmd = "././update_module_json5.sh {}".format(cfg_file)
        ret = subprocess.run([cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
        if ret.returncode:
            print("Error: Update DeviceType failed in {}".format(cfg_file))

    def update_devicetype(self, project_directory):
        module_name = self.get_module_name_of_project(project_directory)
        if not module_name:
            return
        if module_name not in self.modules:
            print("info: {} not belong to this product".format(module_name))
            return

        config_files = self.get_config_file_list(project_directory)
        for i in config_files:
            if i.endswith("config.json"):
                self.update_devicetype_to_config_json(i)
            elif i.endswith("module.json5"):
                self.update_devicetype_to_module_json5(i)
            else:
                print("Error: {} not process".format(i))

        # config_list = [
        #     'entry/src/main/module.json', 'src/main/config.json', 'entry/src/config.json', 'entry/src/main/config.json',
        #     'src/main/module.json', 'application/src/main/module.json'
        # ]

        # for item in config_list:
        #     if os.path.exists(os.path.join(project_directory, item)):
        #         self.update_devicetype_to_json(os.path.join(project_directory, item), self.devicetypes)
        #         return

        # print("error: cannot find config file in project {}".format(project_directory))

    def batch_update_devicetype(self):
        projects = self.get_all_projects()
        for project in projects:
            self.update_devicetype(project)


def main():
    dt = DeviceType()
    dt.batch_update_devicetype()


if __name__ == "__main__":
    sys.exit(main())
